<template>
  <div ref="insideDrawerRef" class="base-inside-drawer" style="display: none;">
    <el-drawer
      ref="drawerRef"
      class="wrapper-border"
      :visible.sync="visibleValue"
      direction="rtl"
      size="100%"
      :show-close="false"
      :modal="false"
      :modal-append-to-body="false"
      :before-close="onBeforeClose"
    >
      <div slot="title" class="drawer-title">
        <i class="el-icon-back" @click="onClose"></i>
        <span>{{ title }}</span>
      </div>

      <div class="drawer-body">
        <slot></slot>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: 'base-inside-drawer',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      visibleValue: false,
      timer: null,
    };
  },
  watch: {
    visible(bool) {
      const $insideDrawerRef = this.$refs.insideDrawerRef;
      if (bool && $insideDrawerRef) {
        $insideDrawerRef.style.display = '';
        this.setDrawerFooterDom($insideDrawerRef);
      } else {
        this.timer = setTimeout(() => {
          $insideDrawerRef.style.display = 'none';
        }, 300);
      }

      this.visibleValue = bool;
    },
  },
  destroyed() {
    clearTimeout(this.timer);
    this.timer = null;
  },
  methods: {
    onBeforeClose(done) {
      this.$emit('update:visible', false);
      done();
    },

    onClose() {
      this.$refs.drawerRef.closeDrawer();
    },

    setDrawerFooterDom(rootRef) {
      this.$nextTick(() => {
        if (rootRef && rootRef.querySelector('.drawer-body')) {
          const drawerFooterEl = rootRef.querySelector('.inside-drawer__footer');
          if (drawerFooterEl) {
            rootRef.querySelector('.drawer-body').style.height = 'calc(100% - 60px)';
            rootRef.querySelector('.el-drawer__body').appendChild(drawerFooterEl);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.base-inside-drawer {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;

  ::v-deep .el-drawer__wrapper {
    position: absolute;
    height: 100%;
    width: 100%;

    .el-drawer__header {
      padding: 12px;
      margin-bottom: 0;
      border-bottom: 1px solid #ddd;

      .drawer-title {
        .el-icon-back {
          margin-right: 12px;
          cursor: pointer;

          &:hover {
            color: #2395FF;
          }
        }
      }
    }

    .el-drawer__body {
      position: relative;

      .drawer-body {
        padding: 12px;
      }

      .inside-drawer__footer {
        height: 60px;
        line-height: 60px;
        border-top: 1px solid #ddd;
        text-align: right;

        > .el-button:last-child {
          margin-right: 12px;
        }
      }
    }
  }
}
</style>
